package com.wlbx.agent.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.adapter.ProductAdapter;
import com.wlbx.agent.adapter.TabTypeAdapter;
import com.wlbx.agent.base.BaseFragment;
import com.wlbx.agent.bean.AgentBean;
import com.wlbx.agent.bean.ProductListBean;
import com.wlbx.agent.bean.ProductSubType;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 产品列表二级tab
 */
public class SubProductListFragment extends BaseFragment {

//    @BindView(R.id.magic_indicator_sub)
//    MagicIndicator magicIndicatorSub;
//    @BindView(R.id.vp_content_sub)
//    ViewPager mViewPagerSub;
    private String productSubType;
//    @BindView(R.id.tfl_sub_type)
//    TagFlowLayout tflSubType;
    private String suitableGroup;
    private List<ProductSubType.DataDTO> mSubTypeList = new ArrayList<>();
    private List<String> mDataList = new ArrayList<>();
    private List<String> mIndexDataList = new ArrayList<>();
    @BindView(R.id.rv_type)
    RecyclerView rvType;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    @BindView(R.id.rv)
    RecyclerView rv;
    private TabTypeAdapter mTabTypeAdapter;
    private ProductAdapter mAdapter;

    static class PageInfo {
        int page = 1;

        void nextPage() {
            page++;
        }

        void reset() {
            page = 1;
        }

        boolean isFirstPage() {
            return page == 1;
        }
    }

    private PageInfo pageInfo = new PageInfo();
    @Override
    protected int getInflateViewId() {
        return R.layout.fragment_sub_product_list;
    }


    public static SubProductListFragment getInstance(){
        return new SubProductListFragment();
    }


    @Override
    public void initData() {

        Bundle bundle = getArguments();
        if (bundle != null) {
            suitableGroup=bundle.getString(Constant.BUNDLE_KEY_PRODUCT_GROUP);
        }
        initTypeAdapter();
        initAdapter();
        getSubType();
        getProductList(pageInfo.page,productSubType,suitableGroup);

    }

    private void initTypeAdapter() {
        mTabTypeAdapter = new TabTypeAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvType.setLayoutManager(manager);
        rvType.setAdapter(mTabTypeAdapter);
        mTabTypeAdapter.setAnimationEnable(true);
        mTabTypeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if(mSubTypeList.get(position).isSelected()) {
                    for (ProductSubType.DataDTO dataDTO : mSubTypeList) {
                        dataDTO.setSelected(false);
                    }
                    mSubTypeList.get(position).setSelected(false);
                    mTabTypeAdapter.notifyDataSetChanged();
                    productSubType="";
                }else {
                    for (ProductSubType.DataDTO dataDTO : mSubTypeList) {
                        dataDTO.setSelected(false);
                    }
                    mSubTypeList.get(position).setSelected(true);
                    mTabTypeAdapter.notifyDataSetChanged();
                    productSubType=mSubTypeList.get(position).getProductSubType();
                }
                pageInfo.reset();
                getProductList(pageInfo.page,productSubType,suitableGroup);
                mAdapter.getLoadMoreModule().setEnableLoadMore(false);
            }
        });
    }

    List<ProductListBean.DataDTO.ListDTO> data;

    private static final int PAGE_SIZE = 10;

    public void getProductList(int page, String productSubType ,String suitableGroup) {
        final Map<String, Object> map = new HashMap<>();
        map.put("curPage",String.valueOf(page));
        map.put("length", String.valueOf(PAGE_SIZE));
        map.put("isWanliPrefer","Y");
        if (!TextUtils.isEmpty(productSubType)){
            map.put("productSubType",productSubType);//产品子类型
        }
        if (!TextUtils.isEmpty(suitableGroup)){
            map.put("suitableGroup",suitableGroup);//产品子类型
        }
        Logger.i("万利优选请求的参数---"+JSON.toJSONString(map));
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getProductList(map)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
//                        Logger.i( response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                            ProductListBean bean=JSON.parseObject(response,ProductListBean.class);

                            if (swipeLayout!=null){
                                swipeLayout.setRefreshing(false);
                            }
                            mAdapter.getLoadMoreModule().setEnableLoadMore(true);

                            data = bean.getData().getList();
                            if (data.size()<=0||data==null){
                                mAdapter.setEmptyView(R.layout.no_data_view);
                            }
                            if (pageInfo.isFirstPage()) {
                                mAdapter.setList(data);
                            } else {
                                mAdapter.addData(data);
                            }

                            if (data.size() < PAGE_SIZE) {
                                mAdapter.getLoadMoreModule().loadMoreEnd();
                            } else {
                                mAdapter.getLoadMoreModule().loadMoreComplete();
                            }

                            pageInfo.nextPage();
                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }

    private void initAdapter() {
        mAdapter = new ProductAdapter(mActivity);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setAdapter(mAdapter);
        mAdapter.setAnimationEnable(true);

        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageInfo.reset();
                getProductList(pageInfo.page,productSubType,suitableGroup);
                mAdapter.getLoadMoreModule().setEnableLoadMore(false);
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//                if (AccountManager.hasUserLogin()) {
//                    ProductListBean.DataDTO.ListDTO bean = mAdapter.getData().get(position);
//                    if (bean.getIsOnline().equals("Y")) {
//                        IntentUtil.goReportActivity(bean.getProductId(), getActivity());
//                    } else {
//                        if (bean.getIsCarFlag().equals("Y")) {
//                            IntentUtil.goOfflineCarActivity(bean.getProductId(), bean.getProductName(), bean.getIsCarFlag(), getActivity());
//                        } else {
//                            IntentUtil.goWanliOfflineActivity(bean.getProductId(), bean.getProductName(), getActivity());
//                        }
//                    }
//                }else {
//                    IntentUtil.goLoginActivity(getActivity());
//                }
                if (AccountManager.hasUserLogin()){
                    ProductListBean.DataDTO.ListDTO bean = mAdapter.getData().get(position);
                    Logger.i(JSON.toJSONString(bean));
                    IntentUtil.goProductDetailActivity(bean,getActivity());

                }else {
                    IntentUtil.goLoginActivity(getActivity());
                }
            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                ProductListBean.DataDTO.ListDTO bean = mAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.iv_logo_url:
                        Toast.makeText(getActivity(), bean.getProductName(), Toast.LENGTH_SHORT).show();

                        break;
                    default:
                        break;
                }
            }
        });


        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getProductList(pageInfo.page,productSubType,suitableGroup);
            }
        });
    }

    @Override
    public void initEvent() {


    }

    public void getSubType() {
        final Map<String, String> map = new HashMap<>();
        map.put("productSubType","");//产品子类型编码
        map.put("productSubTypeName","");//产品子类型名称
//        Logger.i(JSON.toJSONString(map));
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getSubType(map)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
//                        Logger.i("产品类型----" +response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                            ProductSubType bean=JSON.parseObject(response,ProductSubType.class);
                            mSubTypeList = bean.getData();
//                            mSubTypeList.add(0,new ProductSubType.DataDTO("","热销"));
                            for (ProductSubType.DataDTO dataDTO : mSubTypeList) {
                                mDataList.add(dataDTO.getProductSubTypeName());
                                mIndexDataList.add(dataDTO.getProductSubType());
                            }
                            mTabTypeAdapter.setList(mSubTypeList);

//                            initTabAndPager(0);

//                            initSubTypeList(mSubTypeList);

                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (AccountManager.hasUserLogin()){
            getAgentDetail();
        }

    }

    //获取代理人信息
    public void getAgentDetail(){
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getAgentDetail()
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i( response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg  = jsonObject.getString("msg");
                        if("1000".equals(rCode)) {
                            saveAgentInfo(jsonObject);
                        }else {
                            Toast.makeText(mActivity, rMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());
                        Toast.makeText(mActivity,"获取代理人信息失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }
    //保存代理人信息 "data":{"name":"周昕宸","workNo":"60004","image":"https://ceshi.wanlibaoxian.com:444/agentImage/2021/10/09/F1142021100916534165219091532364256624.jpg","loginPwdFlag":"Y","mobile":"13642040397"}}
    private void saveAgentInfo(JSONObject json){
        JSONObject agent = JSON.parseObject(json.getString("data"));
        String name = agent.getString("name");
        String workNo = agent.getString("workNo");
        String image = agent.getString("image");
        String loginPwdFlag = agent.getString("loginPwdFlag");
        String mobile = agent.getString("mobile");
        AgentBean ab = new AgentBean();
        ab.setAccessToken((String) SPUtil.get("Access-Token", ""));
        ab.setPublicKey((String)SPUtil.get("Public-Key",""));
        ab.setName(name);
        ab.setWorkNo(workNo);
        ab.setImage(image);
        ab.setLoginPwdFlag(loginPwdFlag);
        ab.setMobile(mobile);
        SPUtil.putBean(Constant.USER_INFO,"agent",ab);

//        Logger.i(JSON.toJSONString(ab));
        Logger.i(JSON.toJSONString(SPUtil.getBean(Constant.USER_INFO,"agent")));
    }





}
